import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'flutter_huawei_cloud_platform_interface.dart';
import 'src/obs_progress.dart';

/// An implementation of [FlutterHuaweiCloudPlatform] that uses method channels.
class MethodChannelFlutterHuaweiCloud extends FlutterHuaweiCloudPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('flutter_huawei_cloud');

  final eventChannel = const EventChannel('flutter_huawei_cloud_progress');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>(
      'getPlatformVersion',
    );
    return version;
  }

  @override
  Future<void> initialize({
    required String accessKey,
    required String secretKey,
    required String region,
  }) async {
    await methodChannel.invokeMethod('initialize', {
      "accessKey": accessKey,
      "secretKey": secretKey,
      "region": region,
    });
  }

  @override
  Future<String?> uploadFile(
    String bucketName,
    String objectKey,
    String filePath,
  ) async {
    return await methodChannel.invokeMethod('uploadFile', {
      "bucketName": bucketName,
      "objectKey": objectKey,
      "filePath": filePath,
    });
  }

  @override
  Future<Map<String, String>?> uploadMultipleFile(
    String bucketName,
    List<Map<String, String>> files,
  ) async {
    dynamic res = await methodChannel.invokeMethod('uploadMultipleFile', {
      "bucketName": bucketName,
      "files": files,
    });
    if (res is Map) {
      return res.map((k, v) => MapEntry(k.toString(), v.toString()));
    }
    return {};
  }

  @override
  Stream<OBSProgress> get onUploadProgress => eventChannel
      .receiveBroadcastStream('flutter_huawei_cloud_progress')
      .map((event) {
        return OBSProgress(
          objectKey: event['objectKey'],
          bytesSent: event['bytesSent'],
          totalBytes: event['totalBytes'],
        );
      });
}
